<template>
  <van-tabbar
    v-model="active"
    active-color="#ff69b4"
    inactive-color="#999"
    :fixed="true"
    :safe-area-inset-bottom="true"
    :placeholder="true"
    @change="onChange"
  >
    <van-tabbar-item name="home" icon="home-o">
      <span>首页</span>
      <template #icon="props">
        <span :style="{ fontSize: '22px' }">{{ props.active ? '🏠' : '🏡' }}</span>
      </template>
    </van-tabbar-item>

    <van-tabbar-item name="bill" icon="balance-list-o">
      <span>记账</span>
      <template #icon="props">
        <span :style="{ fontSize: '22px' }">{{ props.active ? '💰' : '💵' }}</span>
      </template>
    </van-tabbar-item>

    <van-tabbar-item name="treasury" icon="gold-coin-o">
      <span>金库</span>
      <template #icon="props">
        <span :style="{ fontSize: '22px' }">{{ props.active ? '🏦' : '🏛️' }}</span>
      </template>
    </van-tabbar-item>

    <van-tabbar-item name="diary" icon="notes-o">
      <span>日记</span>
      <template #icon="props">
        <span :style="{ fontSize: '22px' }">{{ props.active ? '📖' : '📕' }}</span>
      </template>
    </van-tabbar-item>

    <van-tabbar-item name="me" icon="user-o" :badge="unreadCount > 0 ? unreadCount : ''">
      <span>我的</span>
      <template #icon="props">
        <span :style="{ fontSize: '22px' }">{{ props.active ? '👤' : '👥' }}</span>
      </template>
    </van-tabbar-item>
  </van-tabbar>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Tabbar as VanTabbar, TabbarItem as VanTabbarItem } from 'vant'
import websocketManager from '@/utils/websocket'

const router = useRouter()
const route = useRoute()

const active = ref('home')
const unreadCount = ref(0)

// 路由映射
const routeMap = {
  home: '/home',
  bill: '/bill/list',
  treasury: '/treasury',
  diary: '/diary/list',
  me: '/profile'
}

// 根据当前路由设置激活项
watch(() => route.path, (newPath) => {
  const entry = Object.entries(routeMap).find(([, path]) => newPath.startsWith(path))
  if (entry) {
    active.value = entry[0]
  }
}, { immediate: true })

// 切换标签
const onChange = (name) => {
  const path = routeMap[name]
  if (path && route.path !== path) {
    router.push(path)
  }
}

// 监听未读消息
const handleWebSocketMessage = (notification) => {
  if (notification.type === 'NOTE_RECEIVED' || notification.type === 'BILL_APPROVAL') {
    unreadCount.value++
  }
}

// 添加 WebSocket 监听
websocketManager.onMessage(handleWebSocketMessage)
</script>

<style scoped>
.van-tabbar {
  background: #fff;
  box-shadow: 0 -2px 12px rgba(255, 154, 158, 0.1);
}

.van-tabbar-item__text {
  font-size: 12px;
  margin-top: 4px;
}

/* 自定义主题色 */
:deep(.van-tabbar-item--active) {
  background: linear-gradient(180deg, rgba(255, 105, 180, 0.05) 0%, transparent 100%);
}

:deep(.van-badge) {
  background: linear-gradient(135deg, #ff69b4 0%, #ff1493 100%);
  border: 2px solid #fff;
}
</style>

